from socket import *
import sys
from time import sleep

class Handle:
    def __init__(self):
        self.server_address = ('127.0.0.1', 8880)
        self.sock = self.__connect_server()

    def __connect_server(self):
        tcp_socket = socket()
        tcp_socket.connect(self.server_address)
        return tcp_socket

    def show_list(self):
        self.sock.send(b"LIST")
        response = self.sock.recv(1024)
        if response == b"OK":
            files = self.sock.recv(1024 * 1024)
            print(files.decode())
        else:
            print("Failed to show file list.")

    def do_exit(self):
        self.sock.send(b"EXIT")
        self.sock.close()
        sys.exit("Thank you for using.")

    def get_file(self, filename):
        request = "GET" + filename
        self.sock.send(request.encode())
        response = self.sock.recv(1024)
        if response == b"OK":
            file = open(filename, 'wb')
            while True:
                data = self.sock.recv(1024)
                if data == b"##":
                    break
                file.write(data)
            file.close()
        else:
            print("File is not exist.")

    def put_file(self, filename):
        try:
            file = open(filename, 'rb')
        except (FileNotFoundError, PermissionError) as e:
            print(f"文件操作失败: {str(e)}")
        else:
            filename = filename.split('/')[-1]
            request = "PUT" + filename
            self.sock.send(request.encode())
            response = self.sock.recv(1024)
            if response == b"OK":
                while True:
                    data = file.read(1024)
                    if not data:
                        break
                    self.sock.send(data)
                file.close()
                sleep(0.1)
                self.sock.send(b"##")
            else:
                print("Failed to upload file.")

class FTPView:
    def __init__(self):
        self.__handle = Handle()

    # @staticmethod
    def __display_menu(self):
        print()
        print("1. 显示文件列表")
        print("2. 下载文件")
        print("3. 上传文件")
        print("4. 退出")
        print()

    def __select_menu(self):
        item = input("请输入选项:")
        if item == '1':
            self.__handle.show_list()
        elif item == '2':
            filename = input("请输入要下载的文件名:")
            self.__handle.get_file(filename)
        elif item == '3':
            filename = input("请输入要上传的文件名:")
            self.__handle.put_file(filename)
        elif item == '4':
            self.__handle.do_exit()
        else:
            print("请输入正确选项")

    def main(self):
        while True:
            self.__display_menu()
            self.__select_menu()

if __name__ == '__main__':
    view = FTPView()
    view.main()